package com.xprophet.crs.jpeg.codec.impl;

import java.io.InputStream;
import java.util.Iterator;

import org.apache.log4j.Logger;

import com.drew.imaging.jpeg.JpegMetadataReader;
import com.drew.imaging.jpeg.JpegProcessingException;
import com.drew.metadata.Directory;
import com.drew.metadata.Metadata;
import com.drew.metadata.MetadataException;
import com.drew.metadata.Tag;
import com.drew.metadata.exif.ExifDirectory;
import com.xprophet.crs.jpeg.codec.IJPEGDecoder;
import com.xprophet.crs.jpeg.codec.model.Fingerprint;

public class ExifDecoderImpl implements IJPEGDecoder {
	
	static Logger log = Logger.getLogger(ExifDecoderImpl.class);
	
	public static final String ID = "exif";
	
	protected Directory exifDir = null;
	
	protected Fingerprint exif = null;

	public boolean parseImage(InputStream is) {
		/*
		 * TODO Arroach 1: This approach reads all types of known Jpeg metadata (at present, Exif and Iptc) in a single
		 * call. In most cases, this is the most appropriate usage.
		 */
		Metadata metadata = null;
		try {
			metadata = JpegMetadataReader.readMetadata(is);
		} catch (JpegProcessingException e) {
			log.error("", e);
			return false;
		}
		exifDir = metadata.getDirectory(ExifDirectory.class);
		//TODO: print all exif info
		
		exif = new Fingerprint();
		exif.setMake(exifDir.getString(ExifDirectory.TAG_MAKE));
		exif.setModel(exifDir.getString(ExifDirectory.TAG_MODEL));
		exif.setEditor(exifDir.getString(ExifDirectory.TAG_SOFTWARE));
		return true;
	}

	public String getData() {
		if (exifDir == null) {
			return "";
		}
		// iterate through tags
		Iterator tags = exifDir.getTagIterator();
		StringBuilder buf = new StringBuilder();
		while (tags.hasNext()) {
			Tag tag = (Tag) tags.next();
			try {
				buf.append(tag.getTagName()).append(":")
				.append(tag.getDescription()).append(";");
			} catch (MetadataException e) {
				log.error("", e);
			}
		}
		return buf.toString();
	}

	public String getEncryptedData() {
		return getData();
	}

	public String getID() {
		return ExifDecoderImpl.ID;
	}

	public Fingerprint getExif() {
		return exif;
	}

	public void setExif(Fingerprint exif) {
		this.exif = exif;
	}

	public Fingerprint getMatchResult(String key, Fingerprint lastResult) {
		// TODO Auto-generated method stub
		return null;
	}

	public void updateMatchMap(Fingerprint newValue) {
		// TODO Auto-generated method stub
		
	}
	
}
